import django
from django.db.models import signals as mods
from django.core import signals as cors
from django.dispatch import receiver
from django.core.cache import cache

from pms import models

# 自定义信号
from yl_pms import utils

import_th_done = django.dispatch.Signal(providing_args=['type'])


def sync_import_th(sender, **kwargs):
    models.SysTaskInit.objects.filter(type=1).update(status=0)


import_th_done.connect(sync_import_th)


@receiver(mods.post_save, sender=models.AuthUser)
@receiver(mods.post_delete, sender=models.AuthUser)
@receiver(mods.post_save, sender=models.BaseProject)
@receiver(mods.post_delete, sender=models.BaseProject)
@receiver(mods.post_save, sender=models.BaseTarget)
@receiver(mods.post_delete, sender=models.BaseTarget)
@receiver(mods.post_save, sender=models.BaseTargetSite)
@receiver(mods.post_delete, sender=models.BaseTargetSite)
@receiver(mods.post_save, sender=models.BaseTargetSiteGroup)
@receiver(mods.post_delete, sender=models.BaseTargetSiteGroup)
@receiver(mods.post_save, sender=models.BaseTargetType)
@receiver(mods.post_delete, sender=models.BaseTargetType)
@receiver(mods.post_save, sender=models.SettingsDataQuota)
@receiver(mods.post_delete, sender=models.SettingsDataQuota)
@receiver(mods.post_save, sender=models.SettingsThreshold)
@receiver(mods.post_delete, sender=models.SettingsThreshold)
def sync_cache(sender, instance, **kwargs):
    # print('-----sync_cache-----')
    try:
        models.SysTaskInit.objects.filter(type=1).update(status=0)
    except():
        msg = 'the table【{}】has not been created yet'.format('sys_task_init')
        utils.print_info(msg)


@receiver(cors.request_finished)
def update_timeout(sender, **kwargs):
    # print('---------update_user_timeout--------------')
    utils.extend_user_expire()
